<?php
$sanitize_all_escapes = true;
$fake_register_globals = false;

require_once("../../globals.php");
require_once("$srcdir/forms.inc");
require_once("$srcdir/calendar.inc");
require_once("$srcdir/acl.inc");
require_once("$srcdir/formatting.inc.php");
require_once("$srcdir/patient.inc");
require_once("$srcdir/amc.php");
include_once("$srcdir/pid.inc");
include_once("$srcdir/encounter.inc");
require_once("$srcdir/patient_provider.inc.php");

if (isset($_GET["set_encounter"])) {
   $set_pid = $_GET["set_pid"] ? $_GET["set_pid"] : $_GET["pid"];
    if ($set_pid && $set_pid != $_SESSION["pid"]) {
        setpid($set_pid);
    }
    
    $_SESSION['encounter']= $_GET["set_encounter"];
    
    setencounter($_GET["set_encounter"]);
}

function check_open_encounter() {
    $query = " SELECT * " .
            " FROM form_encounter " .
            " WHERE closed = 0 AND provider_id = " . $_SESSION['authUserID'];
    $result = sqlStatement($query);
    if (sqlNumRows($result) > 0) {
        return true;
    } else {
        return false;
    }
}

function is_actual_encounter() {
    if ($_SESSION['encounter'] > 0) {
        $query = " SELECT * "
                . " FROM form_encounter "
                . " WHERE encounter = " . $_SESSION['encounter'] . " AND pid = " . $_SESSION['pid'] . " ";
        $result = sqlStatement($query);
        if (sqlNumRows($result) > 0) {
            $row = sqlFetchArray($result);
            if ($row['closed'] == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function close_open_encounters() {
    $query = " UPDATE form_encounter SET closed = 1 WHERE provider_id = " . $_SESSION['authUserID'];
    sqlStatement($query);
}

function fixdate_report($date) {
    
    $temp_date = explode("-", $date);
    $new_date = $temp_date[2] . "/" . $temp_date[1] . "/" . $temp_date[0];
    return $new_date;
}


function fixdate_report_datetime($date) {
    
    $phpdate = strtotime( $date );
    $mysqldate = date( 'd-m-Y', $phpdate );

    return $mysqldate;
}

$query = " SELECT * 
                    FROM `form_encounter` inner join patient_data on ( form_encounter.pid = patient_data.pid )
                    WHERE form_encounter.provider_id = " . $_SESSION['authUserID'] . " AND form_encounter.closed = 0 ";
$result = sqlStatement($query);
$row = sqlFetchArray($result);
$the_pid = $row['pid'];
$the_encounter = $row['encounter'];
?>
<html>

    <head>
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/style_metal.css">
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/nightingale.css" media="screen"/>
        <link rel="stylesheet" type="text/css" href="<?php echo $GLOBALS['webroot'] ?>/interface/themes/jquery.fancybox.css?v=2.1.5" media="screen"/>
        <style type="text/css">@import url(<?php echo $GLOBALS['webroot'] ?>/library/dynarch_calendar.css);</style>

        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/jquery.fancybox.pack.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/expand.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dialog.js"></script>
        <script language="JavaScript">
            $(function() {
                $("#encounter_forms h3.expand").toggler({method: "toggle", speed: 0});
                $("#encounter_forms div.eventos").expandAll({trigger: "h3.expand", ref: "h3.expand", speed: 0});
            });

            // Process click on Delete link.
            function deleteme() {
                dlgopen('del_consulta', '../patient_file/deleter.php?encounterid=<?php echo $encounter; ?>', '_blank', 500, 450);
                return false;
            }

            $(document).ready(function() {
                $('.iframeConsulta').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 800,
                        maxHeight: 500,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {
                        <?php if (isset($_GET["set_encounter"])) { ?>
                                $("#column_left").load("../patient_file/encounter/forms.php?set_encounter=" + <?php echo $_GET["set_encounter"]; ?>);
                        <?php } ?>
                        }//afterClose
                    }); // fancybox
                }); // click

                $('#procedimiento').click(function(e) {
                    e.preventDefault();
                    $("#column_left").load("<?php echo $rootdir . '/patient_file/encounter/load_form.php?formname=procedure_order&set_encounter=' . $_GET["set_encounter"] ?>");
                });

<?php
$queryq = " SELECT * FROM form_encounter WHERE provider_id =  " . $_SESSION['authUserID'] . " AND closed = 0 ";
$resultq = sqlStatement($queryq);
$rowq = sqlFetchArray($resultq);
?>
                $('.iframeSOAP').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 800,
                        maxHeight: 590,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {
<?php if (isset($_GET["set_encounter"])) { ?>
                                $("#column_left").load("../patient_file/encounter/forms.php?set_encounter=" + <?php echo $_GET["set_encounter"]; ?>);
<?php } ?>
                        }//afterClose
                    }); // fancybox
                }); // click

                $('.iframeEX').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 800,
                        maxHeight: 290,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }, // helpers
                        afterClose: function() {
                            <?php if (isset($_GET["set_encounter"])) { ?>
                                $("#column_left").load("../patient_file/encounter/forms.php?set_encounter=" + <?php echo $_GET["set_encounter"]; ?>);
                            <?php } ?>
                        }//afterClose
                    }); // fancybox
                }); // click

                $('.iframe_del').click(function(e) {
                    e.preventDefault();
                    parent.$.fancybox({
                        href: this.href,
                        maxWidth: 800,
                        maxHeight: 290,
                        fitToView: false,
                        type: 'iframe',
                        iframe: {
                               preload: false // fixes issue with iframe and IE
                        },
                        helpers: {
                            overlay: {
                                opacity: 0.3,
                                css: {
                                    'background': 'rgba(255, 254, 254,0.85)'
                                }
                            } // overlay
                        }
                    }); // fancybox
                }); // click

                //Volver al timeline
                $('#enc_list').click(function(e) {
                    e.preventDefault();
                    $("#column_left").load("../patient_file/summary/get_encounters.php?reload=1");
                }); // click

                $(".switch a").click();

                $('#documentosEncounter').attr("style", "display: block !important");
                $('#documentos').attr("style", "display: none !important");

                refreshSignos();
                refreshMedications();
                refreshAllergies();
                refreshProblemasMedicos();
                refreshPrescriptions();

<?php
if (check_open_encounter()) {
    $rquery = " SELECT *, form_encounter.date date2 
                                        FROM `form_encounter` inner join patient_data on ( form_encounter.pid = patient_data.pid )
                                        WHERE form_encounter.provider_id = " . $_SESSION['authUserID'] . " AND form_encounter.closed = 0 ";
    $rresult = sqlStatement($rquery);
    $rrow = sqlFetchArray($rresult);
    $message = "<i class='icon-stethoscope'></i> Cerrar consulta<br><span>Paciente: " . $rrow['fname'] . " " . $rrow['lname'] . "</span><br><span>Fecha: " . $rrow['date2'] . "</span>";

    $docdate = substr($rrow['date2'], 8, 2) . '/' . substr($rrow['date2'], 5, 2) . '/' . substr($rrow['date2'], 0, 4);
    ?>
                    //$("#consulta_close").html("<?php echo $message; ?>");
                    $("#consulta").hide();

                    $("#consulta_close").hide();
                    if (!$("#consulta_close2").length) {
                        $("#buttons").append("<?php echo "<a id='consulta_close2' title='Cerrar Consulta' class='css_button_consulta'><i class='icon-stethoscope'></i> Cerrar consulta<br><span>Paciente: " . $rrow['fname'] . " " . $rrow['lname'] . "</span><br><span>Fecha: " . $docdate . "</span></a>"; ?>")
                        $('#consulta_close2').on("click", function(e) {
                            if (!confirm("Si desea cerrar la consulta anterior seleccione OK. Si quiere cargar la consulta anterior seleccione Cancel.")) {

                                //jQuery.noConflict( true );
                                //$("#info").load( "../patient_file/summary/demographics.php?set_pid=<?php echo $the_pid ?>", function(){
                                $("#column_left").load("../patient_file/encounter/forms.php?set_encounter=<?php echo $the_encounter; ?>");
                                //			});


                            } else {

                                $("#info").load("../patient_file/summary/demographics.php?set_pid=<?php echo $_SESSION['pid']; ?>&closed_old=1");
                            }
                        }); // click
                    }
<?php } ?>

            });
        </script>
    </head>

    <body>
        <div id="consulta_medica" class="border">
            <?php
//DYNAMIC FORM RETREIVAL
            include_once("$srcdir/registry.inc");

            function myGetRegistered($state = "1", $limit = "unlimited", $offset = "0") {
                $sql = "SELECT category, nickname, name, state, directory, id, sql_run, " .
                        "unpackaged, date FROM registry WHERE " .
                        "state LIKE \"$state\" ORDER BY category, priority, name";
                if ($limit != "unlimited")
                    $sql .= " limit $limit, $offset";
                $res = sqlStatement($sql);
                if ($res) {
                    for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
                        $all[$iter] = $row;
                    }
                } else {
                    return false;
                }
                return $all;
            }

            $reg = myGetRegistered();
            /* echo "<pre>";
              print_r($reg);
              echo "</pre>"; */

            if (!empty($reg)) {
                $StringEcho = '<ul id="submenu">';
                foreach ($reg as $entry) {
                    $StringEcho1 = '';
                    $form_value = '';

                    if ($entry['directory'] != 'newpatient') {

                        if ($entry['directory'] == 'examenes') {
                            $StringEcho1.= "<a href='" . $rootdir . '/patient_file/encounter/load_form.php?formname=' . urlencode($entry['directory']) .
                                    "' title='" . xl_form_title("Examen con equ&iacute;po m&eacute;dico") . "' ";
                            $StringEcho1.="class='iframeEX'> <i class='icon-dashboard'></i>";
                            $form_value = 'examenes';
                        }
                        $StringEcho1.="</a>";

                        if ($entry['directory'] == 'soap') {
                            $StringEcho1.= "<a href='" . $rootdir . '/patient_file/encounter/load_form.php?formname=' . urlencode($entry['directory']) .
                                    "' title='" . xl_form_title("Consulta") . "' ";
                            $StringEcho1.="class='iframeSOAP'> <i class='icon-file-text-alt'></i>";
                            $form_value = 'soap';
                        }
                    }


                    $vall = is_actual_encounter();
                    if (acl_check('frms', $form_value) && $vall)
                        $StringEcho .= $StringEcho1;
                }

                foreach ($reg as $entry) {
                    /* echo "<pre>";
                      print_r($entry);
                      echo "</pre>"; */
                    $new_nickname = trim($entry['nickname']);
                    $StringEcho1 = '';
                    $form_value = '';
                    if ($new_nickname != '') {
                        $nickname = $new_nickname;
                    } else {
                        $nickname = $entry['name'];
                    }
                    if ($entry['directory'] != 'newpatient') {

                        if ($entry['directory'] == 'dictation') {
                            $StringEcho1.= "<a href='" . $rootdir . '/patient_file/encounter/load_form.php?formname=' . urlencode($entry['directory']) .
                                    "' title='" . xl_form_title($nickname) . "' ";
                            $StringEcho1.="class='iframeSignos'> <i class='icon-file-text-alt'></i>";
                            $form_value = 'dictation';
                        }
                        if ($entry['directory'] == 'procedure_order') {
                            $StringEcho1.= "<a href='#' title='" . xl_form_title($nickname) . "' ";
                            $StringEcho1.="class='' id='procedimiento'> <i class='icon-info-sign'></i>";
                            $form_value = 'procedure_order';
                        }
                        if ($entry['directory'] == 'vitals') {
                            $StringEcho1.= "<a href='" . $rootdir . '/patient_file/encounter/load_form.php?formname=' . urlencode($entry['directory']) .
                                    "' title='" . xl_form_title($nickname) . "' ";
                            $StringEcho1.="class='iframeSignos'> <i class='icon-gittip'></i>";
                            $form_value = 'vitals';
                        }
                        /* if ($entry['directory'] == 'physical_exam') {
                          $StringEcho1.= "<a href='" . $rootdir . '/patient_file/encounter/load_form.php?formname=' . urlencode($entry['directory']) .
                          "' title='" . xl_form_title($nickname) . "' ";
                          $StringEcho1.="class='iframeConsulta'> <i class='icon-male'></i>";
                          $form_value = 'physical_exam';
                          } */



                        $StringEcho1.="</a>";
                    }
                    $vall = is_actual_encounter();
                    if (acl_check('frms', $form_value) && $vall)
                        $StringEcho .= $StringEcho1;
                }
            }

            $lres = sqlStatement("SELECT * FROM list_options " .
                    "WHERE list_id = 'lbfnames' ORDER BY seq, title");
            if (sqlNumRows($lres)) {
                while ($lrow = sqlFetchArray($lres)) {
                    $form_value = '';
                    $option_id = $lrow['option_id']; // should start with LBF
                    $title = $lrow['title'];
                    $StringEcho1 = "<a href='" . $rootdir . '/patient_file/encounter/load_form.php?formname='
                            . urlencode($option_id) . "' title='" . xl_form_title($title) . "' ";
                    /* echo "<pre>";
                      print_r($lrow);
                      echo "</pre>"; */

                    if ($option_id == 'LBFVacunas') {
                        $StringEcho1.="class='iframeVacunas'>";
                    }

                    if ($option_id == 'LBFMAR') {
                        $StringEcho1.="class='iframeMar'>";
                    }
                    if ($option_id == 'LBFExamenVista') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-eye-open'></i>";
                    }
                    if ($option_id == 'LBFpreop') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-eye-open'></i>";
                    }
                    if ($option_id == 'LBFpostop') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-eye-open'></i>";
                    }
                    if ($option_id == 'LBFcompexamnt') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-eye-open'></i>";
                    }
                    if ($option_id == 'LBFelectrocardiograma') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-check'></i>";
                    }
                    if ($option_id == 'LBFPrenatal') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-user'></i>";
                    }
                    if ($option_id == 'LBFGinecologia') {
                        $StringEcho1.="class='iframeConsulta'><i class='icon-female'></i>";
                    }
                    $StringEcho1.="</a>";

                    $vall = is_actual_encounter();

                    if (acl_check('frms', $option_id) && $vall) {
                        $res = getPatientData($_SESSION['pid']);
                        if (($option_id == 'LBFPrenatal' || $option_id == 'LBFGinecologia') && $res['sex'] == 'Female') {
                            $StringEcho .= $StringEcho1;
                        }
                        if (($option_id != 'LBFPrenatal' && $option_id != 'LBFGinecologia')) {
                            $StringEcho .= $StringEcho1;
                        }
                    }
                }
            }

            $StringEcho.= '<a id="print" title="Imprimir Consulta M&eacute;dica" href="#" onclick="javascript:window.print();"><i class="icon-print"></i></a>';
            $StringEcho.= '<a id="enc_list" title="Regresar" href="#"><i class="icon-undo"></i></a>';

            $dateres = getEncounterDateByEncounter($encounter);
            $encounter_date = date("Y-m-d", strtotime($dateres["date"]));

            $reason = $dateres["reason"];

            $providerIDres = getProviderIdOfEncounter($encounter);
            $providerNameRes = getProviderName($providerIDres);

            $auth_notes_a = acl_check('encounters', 'notes_a');
            $auth_notes = acl_check('encounters', 'notes');
            $auth_relaxed = acl_check('encounters', 'relaxed');

            if (is_numeric($pid)) {
                // Check for no access to the patient's squad.
                $result = getPatientData($pid, "fname,lname,squad");

                if ($result['squad'] && !acl_check('squads', $result['squad'])) {
                    $auth_notes_a = $auth_notes = $auth_relaxed = 0;
                }
                // Check for no access to the encounter's sensitivity level.
                $result = sqlQuery("SELECT sensitivity FROM form_encounter WHERE " .
                        "pid = '$pid' AND encounter = '$encounter' LIMIT 1");
                if ($result['sensitivity'] && !acl_check('sensitivities', $result['sensitivity'])) {
                    $auth_notes_a = $auth_notes = $auth_relaxed = 0;
                }
            }

            if ($GLOBALS['enable_amc_prompting']) {
                ?>
                <!--
                <div class='divEncuesta'>
                                <table>
                                <tr>
                                        <td>
                <?php
                // Display the education resource checkbox (AMC prompting)
                $itemAMC = amcCollect("patient_edu_amc", $pid, 'form_encounter', $encounter);
                ?>
                <?php if (!(empty($itemAMC))) { ?>
                                                                                                                                                <input type="checkbox" id="prov_edu_res" checked>
                <?php } else { ?>
                                                                                                                                                <input type="checkbox" id="prov_edu_res">
                <?php } ?>
                                        </td>
                                        <td>
                                                <span class="text"><?php echo xl('Provided Education Resource(s)?') ?></span>
                                        </td>
                                </tr>
                                <tr>
                                        <td>
                <?php
                // Display the Provided Clinical Summary checkbox (AMC prompting)
                $itemAMC = amcCollect("provide_sum_pat_amc", $pid, 'form_encounter', $encounter);
                ?>
                <?php if (!(empty($itemAMC))) { ?>
                                                                                                                                                <input type="checkbox" id="provide_sum_pat_flag" checked>
                <?php } else { ?>
                                                                                                                                                <input type="checkbox" id="provide_sum_pat_flag">
                <?php } ?>
                                        </td>
                                        <td>
                                                <span class="text"><?php echo xl('Provided Clinical Summary?') ?></span>
                                        </td>
                                </tr>
                <?php
                // Display the medication reconciliation checkboxes (AMC prompting)
                $itemAMC = amcCollect("med_reconc_amc", $pid, 'form_encounter', $encounter);
                ?>
                <?php if (!(empty($itemAMC))) { ?>
                                                                                                                                <tr>
                                                                                                                                        <td>
                                                                                                                                                <input type="checkbox" id="trans_trand_care" checked>
                                                                                                                                        </td>
                                                                                                                                        <td>
                                                                                                                                                <span class="text"><?php echo xl('Transition/Transfer of Care?') ?></span>
                                                                                                                                        </td>
                                                                                                                                </tr>
                                                                                                                        </table>
                                                                                                                        <table style="margin-left:2em;">
                                                                                                                                <tr>
                                                                                                                                        <td>
                    <?php if (!(empty($itemAMC['date_completed']))) { ?>
                                                                                                                                                                                                                    <input type="checkbox" id="med_reconc_perf" checked>
                    <?php } else { ?>
                                                                                                                                                                                                                    <input type="checkbox" id="med_reconc_perf">
                    <?php } ?>
                                                                                                                                        </td>
                                                                                                                                        <td>
                                                                                                                                                <span class="text"><?php echo xl('Medication Reconciliation Performed?') ?></span>
                                                                                                                                        </td>
                                                                                                                                </tr>
                                                                                                                        </table>
                <?php } else { ?>
                                                                                                                        <tr>
                                                                                                                                <td>
                                                                                                                                        <input type="checkbox" id="trans_trand_care">
                                                                                                                                </td>
                                                                                                                                <td>
                                                                                                                                        <span class="text"><?php echo xl('Transition/Transfer of Care?') ?></span>
                                                                                                                                </td>
                                                                                                                        </tr>
                                                                                                                        </table>
                                                                                                                        <table style="margin-left:2em;">
                                                                                                                                <tr>
                                                                                                                                        <td>
                                                                                                                                                <input type="checkbox" id="med_reconc_perf" DISABLED>
                                                                                                                                        </td>
                                                                                                                                        <td>
                                                                                                                                                <span class="text"><?php echo xl('Medication Reconciliation Performed?') ?></span>
                                                                                                                                        </td>
                                                                                                                                </tr>
                                                                                                                        </table>
                <?php } ?>
                </div>
                -->
            <?php } ?>

            <div id="toolBar"><?php echo $StringEcho; ?></div>

            <div id="encounter_forms">  
                <div class="eventos">
                    <h2 style="color: rgb(255, 255, 255); padding-left: 10px;">
                        <i class="icon-stethoscope" style="font-size: 25px;"></i> <?php echo $reason; ?> - <?php echo oeFormatShortDate($encounter_date); ?> 
                        <?php if (acl_check('admin', 'root')) { ?>
                            <a onclick="return deleteme()" class="css_button_left iframe_del" id="del_consulta" href="#" style="border-style: solid;color:#fff;"><i class="icon-remove"></i></a>
                            <?php } ?>
                    </h2>

                    <?php
                    if ($result = getFormByEncounter($pid, $encounter, "id, date, form_id, form_name, formdir, user, deleted")) {
                        $divnos = 1;
                        $existe = false;
                        $form_name = "";
                        $user = "";

                        foreach ($result as $iter) {
                            $existeAutorizacionMedicoInfoPacientesUsuario = existeAutorizacionMedicoInfoPacientesUsuario($iter['user']);

                            $formdir = $iter['formdir'];

                            if ($formdir === 'soap' || $formdir === 'newpatient') {
                                // skip forms whose 'deleted' flag is set to 1
                                if ($iter['deleted'] == 1)
                                    continue;


                                // Skip forms that we are not authorized to see.
                                if ($existeAutorizacionMedicoInfoPacientesUsuario || ($auth_notes_a) ||
                                        ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                        ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry')))
                                    ;
                                else
                                    continue;

                                // $form_info = getFormInfoById($iter['id']);
                                if (strtolower(substr($iter['form_name'], 0, 5)) == 'camos') {
                                    //CAMOS generates links from report.php and these links should
                                    //be clickable without causing view.php to come up unexpectedly.
                                    //I feel that the JQuery code in this file leading to a click
                                    //on the report.php content to bring up view.php steps on a
                                    //form's autonomy to generate it's own html content in it's report
                                    //but until any other form has a problem with this, I will just
                                    //make an exception here for CAMOS and allow it to carry out this
                                    //functionality for all other forms.  --Mark
                                    echo '<tr title="' . xl('Edit form') . '" ' .
                                    'id="' . $formdir . '~' . $iter['form_id'] . '">';
                                } else {

                                    echo '<tr title="' . xl('Edit form') . '" ' .
                                    'id="' . $formdir . '~' . $iter['form_id'] . '" class="text onerow">';
                                }
                                $user = getNameFromUsername($iter['user']);

                                $form_name = ($formdir == 'newpatient') ? "Resumen"/* xl('Patient Encounter') */ : xl_form_title($iter['form_name']);


                                echo "<h3 class='expand'>";
                                // Figure out the correct author (encounter authors are the '$providerNameRes', while other
                                // form authors are the '$user['fname'] . "  " . $user['lname']').
                                if ($formdir == 'newpatient') {
                                    $form_author = $providerNameRes;
                                } else {
                                    $form_author = $user['fname'] . "  " . $user['lname'];
                                }
                                if ($form_name === 'SOEP') {
                                    $form_name = "Consulta ";
                                }
                                echo "<i class='icon-circle-arrow-right'></i> $form_name <span>por " . htmlspecialchars($form_author) . "</span>";
                                echo "</h3>";
                                echo "<div class='collapse divConsulta' id='diiivid_$divnos'>";

                                $last = $form_name;


                                if ((($auth_notes_a) ||
                                        ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                        ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry'))) && acl_check('admin', 'root'))
                                    echo "<a href='$rootdir/patient_file/encounter/view_form.php?" .
                                    "formname=" . $formdir . "&id=" . $iter['form_id'] . "' class='css_button iframeConsulta'><i class='icon-edit'></i></a>";

                                if (acl_check('admin', 'root')) {
                                    if ($formdir != 'newpatient') {
                                        // a link to delete the form from the encounter
                                        echo "<a href='$rootdir/patient_file/encounter/delete_form.php?" .
                                        "formname=" . $formdir .
                                        "&id=" . $iter['id'] .
                                        "&encounter=" . $encounter .
                                        "&pid=" . $pid .
                                        "' class='css_button ";
                                        if ($formdir == 'vitals') {
                                            echo "iframeSignos";
                                        } else {
                                            echo "iframeConsulta";
                                        }
                                        echo "' title='" . xl('Delete this form') . "'><i class='icon-remove'></i></a>";
                                    } /* else {
                                      ?><a href='javascript:;' class='css_button_small' style='color:gray'><?php xl('Delete', 'e'); ?></a><?php
                                      } */
                                }

                                // Use the form's report.php for display.  Forms with names starting with LBF
                                // are list-based forms sharing a single collection of code.
                                //
							
                            if (substr($formdir, 0, 3) == 'LBF') {
                                    include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
                                    call_user_func("lbf_report", $pid, $encounter, 2, $iter['form_id'], $formdir);
                                } else {
                                    //echo $GLOBALS['incdir'] . "/forms/$formdir/report.php";
                                    include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
                                    call_user_func($formdir . "_report", $pid, $encounter, 2, $iter['form_id']);
                                }

                                echo "</div>";
                                $divnos = $divnos + 1;
                            }
                        }

                        foreach ($result as $iter) {
                            $existeAutorizacionMedicoInfoPacientesUsuario = existeAutorizacionMedicoInfoPacientesUsuario($iter['user']);

                            $formdir = $iter['formdir'];
                            if ($formdir === 'procedure_order') {

                                if ($iter['deleted'] == 1)
                                    continue;

                                // Skip forms that we are not authorized to see.
                                if (($existeAutorizacionMedicoInfoPacientesUsuario) || ($auth_notes_a) ||
                                        ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                        ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry')))
                                    ;
                                else
                                    continue;
                                $form_name = ($formdir == 'newpatient') ? "Resumen"/* xl('Patient Encounter') */ : xl_form_title($iter['form_name']);
                                $user = getNameFromUsername($iter['user']);
                                $existe = true;
                            }
                        }
                        if ($existe) {
                            echo "<h3 class='expand'>";

                            $form_author = $user['fname'] . "  " . $user['lname'];

                            echo "<i class='icon-circle-arrow-right'></i> $form_name <span>por " . htmlspecialchars($form_author) . "</span>";
                            echo "</h3>";
                            echo "<div class='collapse divConsulta' id='divid_$divnos'>";
                            foreach ($result as $iter) {
                                $formdir = $iter['formdir'];
                                if ($formdir === 'procedure_order') {
                                    $existeAutorizacionMedicoInfoPacientesUsuario = existeAutorizacionMedicoInfoPacientesUsuario($iter['user']);
                                    // skip forms whose 'deleted' flag is set to 1
                                    if ($iter['deleted'] == 1)
                                        continue;

                                    // Skip forms that we are not authorized to see.
                                    if (($existeAutorizacionMedicoInfoPacientesUsuario) || ($auth_notes_a) ||
                                            ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                            ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry')))
                                        ;
                                    else
                                        continue;

                                    echo "<div class='divConsulta'>";
                                    // $form_info = getFormInfoById($iter['id']);
                                    if (strtolower(substr($iter['form_name'], 0, 5)) == 'camos') {
                                        echo '<tr title="' . xl('Edit form') . '" ' .
                                        'id="' . $formdir . '~' . $iter['form_id'] . '">';
                                    } else {
                                        echo '<tr title="' . xl('Edit form') . '" ' .
                                        'id="' . $formdir . '~' . $iter['form_id'] . '" class="text onerow">';
                                    }


                                    // Skip forms that we are not authorized to see.
                                    if (($auth_notes_a) ||
                                            ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                            ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry'))) {
                                        
                                    }
                                    /* echo "<a href='$rootdir/patient_file/encounter/view_form.php?" .
                                      "formname=" . $formdir . "&id=" . $iter['form_id'] . "' class='css_button iframeConsulta'><i class='icon-edit'></i></a>"; */

                                    if (acl_check('admin', 'root')) {
                                        if ($formdir != 'newpatient') {
                                            // a link to delete the form from the encounter
                                            echo "<a href='$rootdir/patient_file/encounter/delete_form.php?" .
                                            "formname=" . $formdir .
                                            "&id=" . $iter['id'] .
                                            "&encounter=" . $encounter .
                                            "&pid=" . $pid .
                                            "' class='css_button ";
                                            if ($formdir == 'vitals') {
                                                echo "iframeSignos";
                                            } else {
                                                echo "iframeConsulta";
                                            }
                                            echo "' title='" . xl('Delete this form') . "'><i class='icon-remove'></i></a>";
                                        }
                                    }

                                    if (substr($formdir, 0, 3) == 'LBF') {
                                        include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");

                                        call_user_func("lbf_report", $pid, $encounter, 2, $iter['form_id'], $formdir);
                                    } else {
                                        include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");

                                        //echo "/forms/$formdir/report.php";
                                        call_user_func($formdir . "_report", $pid, $encounter, 2, $iter['form_id']);
                                    }

                                    echo "</div>";
                                }
                            }
                            echo "</div>";
                            $divnos = $divnos + 1;
                        }
                        foreach ($result as $iter) {

                            $existeAutorizacionMedicoInfoPacientesUsuario = existeAutorizacionMedicoInfoPacientesUsuario($iter['user']);

                            $formdir = $iter['formdir'];

                            if ($formdir !== 'procedure_order') {
                                // skip forms whose 'deleted' flag is set to 1
                                if ($iter['deleted'] == 1)
                                    continue;

                                if ($formdir === 'soap' || $formdir === 'newpatient')
                                    continue;

                                // Skip forms that we are not authorized to see.
                                if ($existeAutorizacionMedicoInfoPacientesUsuario || ($auth_notes_a) ||
                                        ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                        ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry')))
                                    ;
                                else
                                    continue;

                                // $form_info = getFormInfoById($iter['id']);
                                if (strtolower(substr($iter['form_name'], 0, 5)) == 'camos') {
                                    //CAMOS generates links from report.php and these links should
                                    //be clickable without causing view.php to come up unexpectedly.
                                    //I feel that the JQuery code in this file leading to a click
                                    //on the report.php content to bring up view.php steps on a
                                    //form's autonomy to generate it's own html content in it's report
                                    //but until any other form has a problem with this, I will just
                                    //make an exception here for CAMOS and allow it to carry out this
                                    //functionality for all other forms.  --Mark
                                    echo '<tr title="' . xl('Edit form') . '" ' .
                                    'id="' . $formdir . '~' . $iter['form_id'] . '">';
                                } else {

                                    echo '<tr title="' . xl('Edit form') . '" ' .
                                    'id="' . $formdir . '~' . $iter['form_id'] . '" class="text onerow">';
                                }
                                $user = getNameFromUsername($iter['user']);

                                $form_name = ($formdir == 'newpatient') ? "Resumen"/* xl('Patient Encounter') */ : xl_form_title($iter['form_name']);


                                echo "<h3 class='expand'>";
                                // Figure out the correct author (encounter authors are the '$providerNameRes', while other
                                // form authors are the '$user['fname'] . "  " . $user['lname']').
                                if ($formdir == 'newpatient') {
                                    $form_author = $providerNameRes;
                                } else {
                                    $form_author = $user['fname'] . "  " . $user['lname'];
                                }
                                echo "<i class='icon-circle-arrow-right'></i> $form_name <span>por " . htmlspecialchars($form_author) . "</span>";
                                echo "</h3>";
                                echo "<div class='collapse divConsulta' id='diiivid_$divnos'>";

                                $last = $form_name;


                                if ((($auth_notes_a) ||
                                        ($auth_notes && $iter['user'] == $_SESSION['authUser']) ||
                                        ($auth_relaxed && ($formdir == 'sports_fitness' || $formdir == 'podiatry'))) && acl_check('admin', 'root'))
                                    echo "<a href='$rootdir/patient_file/encounter/view_form.php?" .
                                    "formname=" . $formdir . "&id=" . $iter['form_id'] . "' class='css_button iframeConsulta'><i class='icon-edit'></i></a>";

                                if (acl_check('admin', 'root')) {
                                    if ($formdir != 'newpatient') {
                                        // a link to delete the form from the encounter
                                        echo "<a href='$rootdir/patient_file/encounter/delete_form.php?" .
                                        "formname=" . $formdir .
                                        "&id=" . $iter['id'] .
                                        "&encounter=" . $encounter .
                                        "&pid=" . $pid .
                                        "' class='css_button ";
                                        if ($formdir == 'vitals') {
                                            echo "iframeSignos";
                                        } else {
                                            echo "iframeConsulta";
                                        }
                                        echo "' title='" . xl('Delete this form') . "'><i class='icon-remove'></i></a>";
                                    } /* else {
                                      ?><a href='javascript:;' class='css_button_small' style='color:gray'><?php xl('Delete', 'e'); ?></a><?php
                                      } */
                                }

                                // Use the form's report.php for display.  Forms with names starting with LBF
                                // are list-based forms sharing a single collection of code.
                                //
							
                            if (substr($formdir, 0, 3) == 'LBF') {
                                    include_once($GLOBALS['incdir'] . "/forms/LBF/report.php");
                                    call_user_func("lbf_report", $pid, $encounter, 2, $iter['form_id'], $formdir);
                                } else {
                                    //echo $GLOBALS['incdir'] . "/forms/$formdir/report.php";
                                    include_once($GLOBALS['incdir'] . "/forms/$formdir/report.php");
                                    call_user_func($formdir . "_report", $pid, $encounter, 2, $iter['form_id']);
                                }

                                echo "</div>";
                                $divnos = $divnos + 1;
                            }
                        }
                    }
                    if ($_SESSION['encounter'] != 0) {
                        $query = " SELECT * FROM prescriptions WHERE patient_id = " . $_SESSION['pid'] . " AND encounter =  " . $_SESSION['encounter'];
                        $res = sqlStatement($query);
                        while ($row = sqlFetchArray($res)) {
                            echo "<h3 class='expand'>";
                            echo "<i class='icon-circle-arrow-right'></i> Prescripci&oacuten <span>por " . htmlspecialchars($form_author) . "</span>";
                            echo "</h3>";
                            echo "<div class='collapse divConsulta' id='divid_$divnos'>";
                            //echo "<a href='$rootdir/patient_file/encounter/view_form.php?" .
                            //"formname=" . $formdir . "&id=" . $iter['form_id'] . "' class='css_button iframeConsulta'><i class='icon-edit'></i></a>";
                            //delete option
                            if (acl_check('admin', 'root')) {
                                echo "<a id='borrar" . $row['id'] . "' class='css_button iframeConsulta' title='Borrar' href='" . $web_root . "/patients/deleter.php?prescription=" . $row['id'];
                                echo "&medico=1&set_pid=$pid'>";
                                echo "<i class='icon-remove'></i></a>";

                                echo "<a id='editar" . $row['id'] . "' class='css_button iframeConsulta' title='Editar' href='" . $web_root . "/controller.php?prescription&edit&id=" . $row['id'] . "'>";
                                echo "<i class='icon-edit'></i></a>";
                            }

                            //echo "<pre>";
                            //print_r($row);
                            //echo "</pre>";
                            echo "<span class='bold'>Medicamento:</span> " . $row['drug'] . "<br>";
                            echo "<span class='bold'>Unidades m&eacutedicas:</span> " . $row['size'] . "<br>";
                            echo "</div>";
                            $divnos = $divnos + 1;
                        }

                        $query = " SELECT * FROM lists l inner join issue_encounter ie on (l.id = ie.list_id) "
                                . " WHERE l.pid = " . $_SESSION['pid'] . " AND ie.encounter =  " . $_SESSION['encounter']
                                . " order by l.date desc ";
                        $res = sqlStatement($query);
                        while ($row = sqlFetchArray($res)) {
                            echo "<h3 class='expand'>";
                            $mytype = '';
                            switch ($row['type']) {
                                case 'medical_problem':
                                    $mytype = 'Diagn&oacutesticos M&eacutedicos';
                                    break;
                                case 'allergy':
                                    $mytype = 'Alergias';
                                    break;
                                case 'medication':
                                    $mytype = 'Tratamientos';
                                    break;
                            }
                            echo "<i class='icon-circle-arrow-right'></i> " . $mytype . " <span>por " . htmlspecialchars($form_author) . "</span>";
                            echo "</h3>";
                            echo "<div class='collapse divConsulta' id='divid_$divnos'>";
                            //echo "<a href='$rootdir/patient_file/encounter/view_form.php?" .
                            //"formname=" . $formdir . "&id=" . $iter['form_id'] . "' class='css_button iframeConsulta'><i class='icon-edit'></i></a>";
                            //if( $row['type'] == 'medical_problem'){
                            //delete option
                            if (acl_check('admin', 'root')) {
                                echo "<a href=' "
                                . " /Bolivar/patients/deleter.php?issue=" . $row['id'] . "&medico=1&set_pid= $pid "
                                . " ' class='css_button ";
                                if ($formdir == 'vitals') {
                                    echo "iframeSignos";
                                } else {
                                    echo "iframeConsulta";
                                }
                                echo "' title='" . xl('Delete this form') . "'><i class='icon-remove'></i></a>";
                            }
                            echo "<span class='bold'>T&iacutetulo:</span> " . $row['title'] . "<br>";
                            if ($row['enddate'] != '') {
                                echo "<span class='bold'>Periodo:</span> " . fixdate_report($row['begdate']) . " - " . fixdate_report($row['enddate']) . "<br>";
                            } else {
                                echo "<span class='bold'>Periodo:</span> " . fixdate_report($row['begdate']) . " - " . xl('present') . "<br>";
                            }

                            echo "<span class='bold'>Comentarios:</span> " . $row['comments'] . "<br>";
                            echo "</div>";
                            $divnos = $divnos + 1;
                        }
                        $query = " SELECT * FROM documents d  "
                                . " WHERE d.encounter = " . $_SESSION['encounter']
                                . " AND d.FromEX!=1 order by d.date desc ";
                        $res = sqlStatement($query);
                        while ($row = sqlFetchArray($res)) {
                            echo "<h3 class='expand'>";

                            echo "<i class='icon-circle-arrow-right'></i> " . " Documento " . " <span>por " . htmlspecialchars($form_author) . "</span>";
                            echo "</h3>";
                            echo "<div class='collapse divConsulta' id='divid_$divnos'>";
                            echo "<span class='bold'>Nombre: </span><span class=text>" . basename($row['url']) . "</span> <br>";
                            echo "<span class='bold'>Link de descarga: </span><span class=text>" . "<a href='../download.php?filename=" . $row['url'] . "' >Click aquí para descargar el archivo.</a>" . " </span> <br>";
                            echo "</div>";
                            $divnos = $divnos + 1;
                        }
                    }
                    ?>
                </div>
            </div>
        </div> <!-- consulta medica -->
    </body>
</html>